#!/usr/bin/env python
import os
import sys
import subprocess

def check_import(module_name):
    """检查模块是否可以导入"""
    try:
        __import__(module_name)
        return True, f"{module_name} 导入成功"
    except ImportError as e:
        return False, f"{module_name} 导入失败: {e}"

def main():
    print("=== Django 诊断工具 ===\n")
    
    # 检查Python版本
    print(f"1. Python版本: {sys.version}")
    print(f"   Python路径: {sys.executable}")
    
    # 检查当前目录
    print(f"\n2. 当前工作目录: {os.getcwd()}")
    
    # 检查Python路径
    print(f"\n3. Python路径:")
    for i, path in enumerate(sys.path[:5]):
        print(f"   {i}: {path}")
    
    # 检查必要的模块
    print(f"\n4. 检查必要的模块:")
    modules = ['django', 'rest_framework', 'pymysql', 'pypinyin', 'requests']
    
    for module in modules:
        success, message = check_import(module)
        status = "✓" if success else "✗"
        print(f"   {status} {message}")
    
    # 检查Django设置
    print(f"\n5. 检查Django设置:")
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webmgr.settings')
    print(f"   DJANGO_SETTINGS_MODULE: {os.environ.get('DJANGO_SETTINGS_MODULE')}")
    
    try:
        import django
        django.setup()
        print("   ✓ Django设置成功")
        
        # 检查应用
        from django.conf import settings
        print(f"   INSTALLED_APPS: {settings.INSTALLED_APPS}")
        
        # 检查数据库
        print(f"   DATABASES: {settings.DATABASES['default']['ENGINE']}")
        
    except Exception as e:
        print(f"   ✗ Django设置失败: {e}")
    
    # 检查文件是否存在
    print(f"\n6. 检查关键文件:")
    files_to_check = [
        'manage.py',
        'webmgr/settings.py',
        'webmgr/urls.py',
        'spideradmin/views.py',
        'spideradmin/models.py'
    ]
    
    for file_path in files_to_check:
        exists = os.path.exists(file_path)
        status = "✓" if exists else "✗"
        print(f"   {status} {file_path}: {'存在' if exists else '不存在'}")
    
    # 尝试运行Django命令
    print(f"\n7. 尝试运行Django命令:")
    try:
        result = subprocess.run([
            sys.executable, 'manage.py', 'check'
        ], capture_output=True, text=True, cwd=os.getcwd())
        
        if result.returncode == 0:
            print("   ✓ Django检查通过")
        else:
            print(f"   ✗ Django检查失败: {result.stderr}")
    except Exception as e:
        print(f"   ✗ 运行Django命令失败: {e}")

if __name__ == "__main__":
    main() 